<template>
  <div>
    <img :src="item.image" alt="" width="100%" height="200">
    <h3>{{ item.title }}</h3>
    <p>{{ item.desc }}</p>
    <p>{{ item.price }}</p>
    <!-- 评论列表 -->
    <h3>评论列表</h3>
    <dl v-for="(v, i) in item.message" :key="i" class="message-item">
      <dt>
        <img :src="v.avator" alt="">
      </dt>
      <dd>
        <h4>{{ v.nickname }}</h4>
        <p>{{ v.content }}</p>
        <div class="btm">
          <span>赞</span>
          <span>{{ v.datetime }}</span>
        </div>
      </dd>
    </dl>

    <!-- 添加评论 -->
    <van-cell-group inset>
      <van-field v-model="message" rows="4" autosize label="评论" type="textarea" maxlength="50" placeholder="请输入评论"
        show-word-limit />
    </van-cell-group>
    <van-button type="primary" block @click="addMessage">确定添加评论</van-button>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router'

const { params } = useRoute();
const router = useRouter()
const id = params.id
const item = ref({});

const getItem = async () => {
  const resp = await axios.get('/list/detail', { params: { id } });
  console.log(resp.data);
  item.value = resp.data;
}

getItem()

const message = ref('')

const addMessage = () => {

  if(localStorage.getItem('token')) {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    item.value.message.push({
      avator: userInfo.avator,
      nickname: userInfo.nickname,
      content: message.value,
      datetime: new Date().toLocaleString()
    })
  } else {
    router.push('/login')
  }
}
</script>


<style lang="scss">
.message-item {
  display: flex;
  padding: 6px;
  border-bottom: 1px solid #ccc;

  dd {
    flex: 1;
  }

  img {
    border-radius: 50%;
    margin-right: 10px;
  }

  .btm {
    display: flex;
    justify-content: space-between;
  }
}
</style>